package com.zf.shuashua.ui.home;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.meis.base.mei.base.BaseFragment;
import com.meis.base.mei.utils.NumberUtils;
import com.meis.base.mei.utils.SoftKeyboardUtils;
import com.zf.shuashua.R;
import com.zf.shuashua.api.Store;
import com.zf.shuashua.bean.comment.CommentEntity;
import com.zf.shuashua.event.UpdateCommentNumberEvent;
import com.zf.shuashua.ui.dialog.BottomCommentDialog;
import com.zf.shuashua.ui.mine.LoginActivity;

import org.greenrobot.eventbus.EventBus;

public class HomeCommentFragment extends BaseFragment {

    private BottomSheetBehavior mBehavior;

    public static final String VIDEO_ID = "video_id";
    public static final String HEADER_URL = "header_url";
    public static final String COMMENT_NUMBER = "comment_num";
    public static final String VIDEO_ADAPTER_POSITION = "adapter_position";

    private RelativeLayout mBehaviorLayout;

    private OnCommentListener mListener;

    private ImageView mIvHeader;
    private TextView mTvTotal;

    private String videoId;
    private String headerUrl;
    private int commentNum;
    private int updateVideoListPos = 0;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            mBehaviorLayout.postDelayed(() -> SoftKeyboardUtils.hideSoftInput(getActivity()), 100);
        }
    };

    private CommentListFragment mCommentListFragment;
    private BottomCommentDialog mBottomCommentDialog;

    public interface OnCommentListener {
        void onDismiss();

        void onSlide(float ratio);
    }

    public void setOnCommentListener(OnCommentListener listener) {
        mListener = listener;
    }

    public static HomeCommentFragment newInstance(String videoId, String headerUrl, int commentNum, int position) {
        Bundle args = new Bundle();
        args.putString(VIDEO_ID, videoId);
        args.putString(HEADER_URL, headerUrl);
        args.putInt(COMMENT_NUMBER, commentNum);
        args.putInt(VIDEO_ADAPTER_POSITION, position);
        HomeCommentFragment fragment = new HomeCommentFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected void initView() {
        mBehaviorLayout = getView().findViewById(R.id.behavior_layout);
        mIvHeader = getView().findViewById(R.id.iv_header);
        mTvTotal = findViewById(R.id.tv_total);

        if (getArguments() != null) {
            videoId = getArguments().getString(VIDEO_ID, "");
            headerUrl = getArguments().getString(HEADER_URL, "");
            commentNum = getArguments().getInt(COMMENT_NUMBER, 0);
            updateVideoListPos = getArguments().getInt(VIDEO_ADAPTER_POSITION, 0);
        }

        // mTvTotal.setText(getString(R.string.comment_count, commentNum));
        setCommentNum(commentNum);

        mBehavior = BottomSheetBehavior.from(mBehaviorLayout);
        mBehavior.setPeekHeight(0);
        mBehavior.setState(BottomSheetBehavior.STATE_HIDDEN);

        mBehavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
            @Override
            public void onStateChanged(@NonNull View view, int newState) {
                if (newState == BottomSheetBehavior.STATE_HIDDEN) {
                    mBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
                } else if (newState == BottomSheetBehavior.STATE_COLLAPSED) {
                    if (mListener != null) {
                        mListener.onDismiss();
                    }
                }
            }

            @Override
            public void onSlide(@NonNull View view, float v) {

            }
        });

        findViewById(R.id.view_top).setOnClickListener(v -> {
            hideBehavior();
        });

        findViewById(R.id.iv_back).setOnClickListener(v -> {
            hideBehavior();
        });

        loadRootFragment(R.id.fl_recycler, mCommentListFragment = CommentListFragment.newInstance(videoId));
        mCommentListFragment.setOnOperateListener(new CommentListFragment.OnOperateListener() {
            @Override
            public void onDeleteComment(int deleteNum) {
                commentNum -= deleteNum;
                if (commentNum < 0) commentNum = 0;
                // mTvTotal.setText(getString(R.string.comment_count, commentNum));
                setCommentNum(commentNum);

                EventBus.getDefault().post(new UpdateCommentNumberEvent(videoId, commentNum, updateVideoListPos));
            }

            @Override
            public void onAddReply() {
                addCommentNumber();
            }
        });

        if (!TextUtils.isEmpty(headerUrl)) {
            Glide.with(getActivity())
                    .load(headerUrl)
                    .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                    .into(mIvHeader);
        }

        findViewById(R.id.comment_layout).setOnClickListener(v -> {
            if (!Store.getInstance().isLogin()) {
                jumpLogin();
                return;
            }

            showDialog(mBottomCommentDialog = new BottomCommentDialog(videoId, "", 0, "", false, false, new BottomCommentDialog.OnPublishListener() {
                @Override
                public void onPublish(int position, boolean isAt, boolean isLevel2Reply, CommentEntity entity) {
                    if (isAt) return;
                    if (mCommentListFragment != null) {
                        mCommentListFragment.insertData(position, entity);
                    }
                    addCommentNumber();

                    if (mCommentListFragment.isItemEmptyPage()) {
                        mCommentListFragment.setItemEmptyPage(false);
                        mCommentListFragment.removeItemEmpty();
                    }
                }

                @Override
                public void onCloseKeyboard() {
                    mHandler.sendEmptyMessage(1);
                }
            }));

        });
    }

    // 增加评论数据
    private void addCommentNumber() {
        commentNum += 1;
        // mTvTotal.setText(getString(R.string.comment_count, commentNum));
        setCommentNum(commentNum);

        EventBus.getDefault().post(new UpdateCommentNumberEvent(videoId, commentNum, updateVideoListPos));
    }

    private void setCommentNum(int num) {
        mTvTotal.setText(NumberUtils.INSTANCE.convertOneDecimalW(num) + "条评论");
    }


    private void jumpLogin() {
        getActivity().startActivity(new Intent(getActivity(), LoginActivity.class));
    }

    public void showBehavior() {
        if (mBehavior != null)
            mBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);
    }

    public void hideBehavior() {
        if (mBehavior != null) {
            mBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
        }
    }

    public boolean isShowing() {
        return mBehavior.getState() == BottomSheetBehavior.STATE_EXPANDED;
    }

    @Override
    protected void initData() {

    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_home_comment;
    }

    @Override
    public void onDestroy() {
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }
        super.onDestroy();
    }
}
